#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QInputDialog>
#include <QLabel>
#include <QStandardItemModel>
#include <QRandomGenerator>
#include <QTime>
#include <QFileDialog>
#include <QMessageBox>
#include <QTimer>
#include <thread.h>
#include <QThread>
#include <QProgressBar>
#include <mysql.h>
#include <QRandomGenerator>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("界面程序-范浩伟-7月2号");


    //点击菜单栏按钮，打开新页面
    connect(ui->action,&QAction::triggered,this,&MainWindow::ShowNewPage);

    //点击工具栏按钮，打印
    connect(ui->action1,&QAction::triggered,this,&MainWindow::print);
    connect(ui->action2,&QAction::triggered,this,&MainWindow::print);
    connect(ui->action3,&QAction::triggered,this,&MainWindow::print);
    connect(ui->action4,&QAction::triggered,this,&MainWindow::print);
    connect(ui->action5,&QAction::triggered,this,&MainWindow::print);

    //状态栏
    leftStatus = new QLabel("左侧状态");
    leftStatus->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    leftStatus->setMinimumWidth(200);
    ui->statusBar->addWidget(leftStatus, 1);

    rightStatus1 = new QLabel("右侧状态");
    rightStatus1 = new QLabel("右侧状态", this);
    rightStatus1->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    rightStatus1->setMinimumWidth(150);

    rightStatus2 = new QLabel("右侧状态");
    rightStatus2->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    rightStatus2->setMinimumWidth(150);

    QWidget *rightContainer = new QWidget;
    QHBoxLayout *rightLayout = new QHBoxLayout(rightContainer);
    rightLayout->setContentsMargins(0, 0, 0, 0);
    rightLayout->addWidget(rightStatus1);
    rightLayout->addWidget(rightStatus2);

    ui->statusBar->addPermanentWidget(rightContainer);


    //表格
    ui->tableWidget->setSortingEnabled(true);
    connect(ui->pushButton_sort,&QPushButton::clicked,this,&MainWindow::Reverse);

    //树形图


    //写入文件
    connect(ui->pushButton_write,&QPushButton::clicked,this,&MainWindow::Mkdir);

    connect(ui->pushButton_sql,&QPushButton::clicked,[]()
    {
        MySql::getInstance();
        MySql::getInstance()->Insert();
    });

    TreeModel();

    flag = true;

    //TCP发送
    server.listen(QHostAddress::Any,1234);
    socket = new QTcpSocket;
    timer = new QTimer;
    timer->setInterval(500);

    connect(ui->pushButton_send,&QPushButton::clicked,[&]()
    {
        socket->connectToHost("127.0.0.1", 1234);
    });
    connect(timer, &QTimer::timeout, this, &MainWindow::TCPSend);
    connect(socket, &QTcpSocket::connected, [&]()
    {
        timer->start();
    });

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::TreeModel()
{
    model = new QStandardItemModel(0, 5, this);

    QStringList headers;
    headers << "序号" << "随机数1" << "随机数2" << "随机数3" << "随机数3";
    model->setHorizontalHeaderLabels(headers);

    // 生成随机数据
    TreeData();

    ui->treeView->setModel(model);
    ui->treeView->setRootIsDecorated(true);
    ui->treeView->setAlternatingRowColors(true);
    ui->treeView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->treeView->setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(ui->pushButton_zero, &QPushButton::clicked, this, &MainWindow::ToZero);
    connect(ui->pushButton_del, &QPushButton::clicked, this, &MainWindow::Del);

}

void MainWindow::TreeData()
{
    QStringList departments = {"A", "B", "C", "D", "E","F","G","H"};
    QStringList subDepartments = {"I", "II", "III"};

    for (int i = 0; i < departments.size(); ++i)
    {
        QList<QStandardItem*> parentItems;
        QStandardItem *parentItem = new QStandardItem(departments[i]);
        parentItems.append(parentItem);

        for (int j = 0; j < subDepartments.size(); ++j)
        {
            QList<QStandardItem*> childItems;
            QStandardItem *childItem = new QStandardItem(departments[i] + "-" + subDepartments[j]);
            childItems.append(childItem);

            for (int k = 1; k < model->columnCount(); ++k)
            {
                int randomValue = QRandomGenerator::global()->bounded(50);
                childItems.append(new QStandardItem(QString::number(randomValue)));
            }

            parentItem->appendRow(childItems);
        }

        for (int k = 1; k < model->columnCount(); ++k)
        {
            int randomValue = QRandomGenerator::global()->bounded(50);
            parentItems.append(new QStandardItem(QString::number(randomValue)));
        }

        model->appendRow(parentItems);
    }
}

void MainWindow::Mkdir()
{
    QString filePath = QFileDialog::getSaveFileName(this, "保存文件", "", "文本文件 (*.txt);;所有文件 (*)");

    if (!filePath.isEmpty())
    {
        Thread *file = new Thread(filePath);
        QThread* thread = new QThread;
        file->moveToThread(thread);

        connect(thread, &QThread::started, file, &Thread::startWork);
        connect(file, &Thread::finished, thread, &QThread::quit);
        connect(thread, &QThread::finished, thread, &QThread::deleteLater);
        connect(file, &QThread::finished, file, &QThread::deleteLater);

        thread->start();
    }
}

void MainWindow::print()
{
    bool ok;
    QString text = QInputDialog::getText(this,"输入文本","请输入您的文本:",QLineEdit::Normal,"",&ok);
    if (ok && !text.isEmpty())
    {
        rightStatus1->setText("您输入的文本是: " + text);
    }
    qDebug()<<text;
}

void MainWindow::ShowNewPage()
{
    QDialog* newPage = new QDialog;
    newPage->setWindowTitle("新页面");
    newPage->resize(400,400);
    leftStatus->setText("已打开新页面");
    newPage->exec();
    leftStatus->setText("左侧状态");

}

void MainWindow::Reverse()
{

    if(flag)
    {
        ui->tableWidget->sortItems(1, Qt::DescendingOrder);
        flag = false;
    }
    else
    {
        ui->tableWidget->sortItems(1, Qt::AscendingOrder);
        flag = true;
    }

}

void MainWindow::TCPSend()
{

    if (socket->state() != QTcpSocket::ConnectedState)
    {
        return;
    }
    QString str = "hello world!";

    socket->write(str.toUtf8());

    QString message = QString("[%1] 发送: %2").arg(QTime::currentTime().toString("hh:mm:ss.zzz"), str);
    ui->textEdit->append(message);
}

void MainWindow::process(QStandardItem *parent)
{
    for (int row = 0; row < parent->rowCount(); row++)
    {
            for (int col = 0; col < parent->columnCount(); col++)
            {
                QStandardItem *item = parent->child(row, col);
                if (!item)
                    continue;

                if (col > 0) {
                    bool ok;
                    int value = item->text().toInt(&ok);
                    if (ok && value <= 25) {
                        item->setText("0");
                    }
                }

                // 递归处理子节点
                if (item->rowCount() > 0) {
                    process(item);
                }
            }
        }
}

void MainWindow::ToZero()
{
    process(model->invisibleRootItem());
}

void MainWindow::Del()
{
    for (int row = model->rowCount() - 1; row >= 0; row--) {
        if (row % 2 == 0)
            continue;
        model->removeRow(row);
    }
}
